#include	"LogFile.h"

#include	<ctime>
#include	<cstdio>
#include	<cstdlib>
#include	<cstring>
#include	<Path.h>

#if defined(_MSC_VER)
#	pragma	warning(disable: 4996)
#endif

namespace {

	FILE * Create(const char * name, struct tm & now, int index) {
		char path[512] = { 0 };

		if (!Path::Exists("actions/")) Path::Create("actions");

		int offset = snprintf(path, 512, "actions/%04d%02d%02d", now.tm_year + 1900, now.tm_mon + 1, now.tm_mday);
		if (!Path::Exists(path)) Path::Create(path);

		snprintf(path + offset, 512 - offset, "/%s_%04d.log", name, index);
		return fopen(path, "w+");
	}

}

LogFile::LogFile(const std::string & action, size_t max_size)
	: _file(nullptr)
	, _action(action)
	, _max_size(max_size)
	, _last_day(-1)
	, _writed(0)
	, _index(0) {}

LogFile::~LogFile() {
	if (_file) fclose(_file);
}

void LogFile::Write(uint32_t time, uint64_t pid, const std::string & detail) {
	time_t now = (time_t)time;
	struct tm current;

#if defined(_WIN32)
	localtime_s(&current, &now);
#else
	localtime_r(&now, &current);
#endif

	if (_last_day != current.tm_mday) {
		_file = Create(_action.c_str(), current, 0);
		if (!_file) return;

		_last_day = current.tm_mday;
		_index = 0;
	} else if (_writed >= _max_size) {
		_file = Create(_action.c_str(), current, _index + 1);
		if (!_file) return;
		_index++;
	}

	_writed += fprintf(_file, "%04d-%02d-%02d %02d:%02d:%02d|%llu|%s\n",
		current.tm_year + 1900, current.tm_mon + 1, current.tm_mday,
		current.tm_hour, current.tm_min, current.tm_sec,
		pid, detail.c_str());
	fflush(_file);
}